module SearchHelper
  def mark_suggestion(sugg, query)
    sugg.sub(query, "<b>#{query}</b>")
  end

  def isolate_tokens(string)
    result = Array.new
    string.downcase!
    return '' if string.nil? || string.empty?

    if string.include? '('
      first_type = ''
      if (string.index('all(') < string.index('phrase(')) && (string.index('all(') < string.index('exclude(')) && (string.index('all(') < string.index('author('))
        split_string = string.split('all(',2)
        first_type = 'all('
      elsif (string.index('phrase(') < string.index('all(')) && (string.index('phrase(') < string.index('exclude(')) && (string.index('phrase(') < string.index('author('))
        split_string = string.split('phrase(',2)
        first_type = 'phrase('
      elsif (string.index('exclude(') < string.index('all(')) && (string.index('exclude(') < string.index('phrase(')) && (string.index('exclude(') < string.index('author('))
        split_string = string.split('exclude(',2)
        first_type = 'exclude('
      elsif (string.index('author(') < string.index('all(')) && (string.index('author(') < string.index('phrase(')) && (string.index('author(') < string.index('exclude('))
        split_string = string.split('author(',2)
        first_type = 'author('
      else
        split_string = string.split('all(',2)
        first_type = 'all('
      end
      # basic tokens
      result += split_string[0].split(/ /).delete_if {|t| t.strip == ""}.uniq

      # isolate advanced tokens and collect them
      split_string -= [split_string[0]]
      split_string.collect! { |x| first_type + x }
      option_string = split_string.join('')

      arr = option_string.split(')')
      arr.collect! { |x| x.split('(', 2) }
      arr2 = Array.new
      arr.each { |x| arr2 << x[1] unless x[1].empty? }
      arr2.collect! { |x| x.split(' ')}
      arr2.flatten!
      result += arr2
    else
      # basic tokens
      result += query.split(/ /).delete_if {|t| t.strip == ""}.uniq
    end

    result.uniq!
    return result.join(' ')
  end

  def string_to_options(string)

    return result
  end
end
